package com.yanx.framework.advice;

import com.yanx.common.annotation.ApiResult;
import com.yanx.common.annotation.Pagination;
import com.yanx.common.result.IResult;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.converter.StringHttpMessageConverter;

public class BaseResponseBodyAdvice {

    protected boolean isStringConverter(Class converterType) {
        return converterType.equals(StringHttpMessageConverter.class);
    }

    protected boolean isApiResult(MethodParameter returnType) {
        return returnType.hasMethodAnnotation(ApiResult.class);
    }

    protected IResult createApiResult(MethodParameter returnType) {
        ApiResult resultAnnotation = AnnotationUtils.findAnnotation(returnType.getAnnotatedElement(), ApiResult.class);
        Pagination paginationAnnotation = AnnotationUtils.findAnnotation(returnType.getAnnotatedElement(), Pagination.class);
        boolean isPage = paginationAnnotation != null;
        IResult result;
        if (resultAnnotation == null) {
            result = IResult.build(null, isPage);
        } else {
            result = IResult.build(resultAnnotation.resultClass(), isPage);
            result.init(resultAnnotation.successCode(), resultAnnotation.successMsg());
        }
        return result;
    }

}
